#!/usr/bin/env python3
#encoding:UTF-8

#######################################################################
# Copyright (C)                                                       #
# 2016 - 2018 Shangtong Zhang(zhangshangtong.cpp@gmail.com)           #
# 2016 Jan Hakenberg(jan.hakenberg@gmail.com)                         #
# 2016 Tian Jun(tianjun.cpp@gmail.com)                                #
# 2016 Kenta Shimada(hyperkentakun@gmail.com)                         #
# Permission given to modify the code as long as you keep this        #
# declaration at the top                                              #
#######################################################################

from .env import State
from .env import BOARD_ROWS
from .env import BOARD_COLS


def get_all_states_impl(current_state, current_symbol, all_states):
    for i in range(0, BOARD_ROWS):
        for j in range(0, BOARD_COLS):
            # 遍历棋盘所有位置，查找空位
            if current_state.data[i][j] == 0:
                # symbol棋手填补空位，生成新的棋盘状态对象newState
                newState = current_state.next_state(i, j, current_symbol)
                
                # 获得新状态对象hash值
                newHash = newState.hash()
                
                # 判断新棋盘状态是否已经遍历
                if newHash not in all_states.keys():
                    isEnd = newState.is_end()
                    
                    # 将新棋盘状态对象加入到all_states字典集合中
                    all_states[newHash] = (newState, isEnd)
                    
                    # 新棋盘状态若为非终止状态，迭代调用遍历函数
                    #           若为终止状态状态则停止迭代
                    if not isEnd:
                        get_all_states_impl(newState, -current_symbol, all_states)


def get_all_states():
    # 默认先手标志为1
    current_symbol = 1
    # 生成一个初始状态，numpy矩阵为全空
    current_state = State()
    
    # 状态字典,第一个状态为空棋盘
    # all_states的key值为状态的hash值,value为tuple(状态对象，是否结束的Boolean值)
    all_states = dict()
    all_states[current_state.hash()] = (current_state, current_state.is_end())
    
    # 调用函数，遍历所有状态
    get_all_states_impl(current_state, current_symbol, all_states)
    return all_states


# 生成棋盘所有的可能状态, all_states为字典
# all_states的key值为状态的hash值,value为(状态对象，是否结束的Boolean值)
# all possible board configurations
all_states = get_all_states()
